package com.jn.servicedemo.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.jn.servicedemo.R;
import com.jn.servicedemo.constant.Constants;
import com.jn.servicedemo.event.CommendEvent;
import com.jn.servicedemo.event.MessageEvent;
import com.jn.servicedemo.listener.OnMessageChangeListener;
import com.jn.servicedemo.receiver.NotificationReceiver;
import com.jn.servicedemo.views.MainActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainService extends Service {

    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "music_channel";
    private static final String CHANNEL_NAME = "音乐播放控制";

    // 模拟播放状态
    private boolean isPlaying = false;
    // 远程视图，用于自定义通知布局
    private RemoteViews remoteViews;
    private int name = 10;
    private int duration = 10;
    private OnMessageChangeListener mListener;
    private Handler mActivityHandler;

    public void setMessageChangeListener(OnMessageChangeListener listener) {
        mListener = listener;
    }

    public void setHandler(Handler activityHandler) {
        mActivityHandler = activityHandler;
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String command = intent.getStringExtra("command");
            Log.d("asdf", "=======onReceive=======" + command);
            if (command != null) {
                switch (command) {
                    case Constants.COMMAND_PLAY:
                        play();
                        break;
                    case Constants.COMMAND_PAUSE:
                        pause();
                        break;
                    case Constants.COMMAND_LAST:
                        last();
                        break;
                    case Constants.COMMAND_NEXT:
                        next();
                        break;
                }
            }
        }
    };

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("asdf", "===========onCreate==========");
        EventBus.getDefault().register(this);
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_ACTIVITY_TO_SERVICE);
        registerReceiver(mReceiver, intentFilter);
        // 初始化远程视图
        remoteViews = new RemoteViews(getPackageName(), R.layout.notification_custom);
        // 创建通知渠道
        createNotificationChannel();

        // 设置通知点击事件和按钮事件
        setupNotificationActions();

        // 更新通知显示
        updateNotification();

        // 启动前台服务
        startForeground(NOTIFICATION_ID, buildNotification());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String command = intent.getStringExtra("command");
        Log.d("asdf", "=======onStartCommand=======" + command);
        if (command != null) {
            switch (command) {
                case Constants.COMMAND_PLAY:
                    play();
                    break;
                case Constants.COMMAND_PAUSE:
                    pause();
                    break;
                case Constants.COMMAND_LAST:
                    last();
                    break;
                case Constants.COMMAND_NEXT:
                    next();
                    break;
            }
        }

        if (intent != null && intent.getAction() != null) {
            // 处理从广播接收器传来的动作
            switch (intent.getAction()) {
                case NotificationReceiver.ACTION_PREV:
                    last();
                    break;
                case NotificationReceiver.ACTION_PLAY_PAUSE:
                    if (isPlaying) {
                        pause();
                    } else {
                        play();
                    }
                    break;
                case NotificationReceiver.ACTION_NEXT:
                    next();
                    break;
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    // 创建通知渠道（Android 8.0+ 必需）
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_LOW
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(channel);
            }
        }
    }

    // 设置通知的点击事件和按钮事件
    private void setupNotificationActions() {
        // 设置通知整体点击事件（打开主界面）
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this,
                0,
                intent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.iv_album, pendingIntent);

        // 设置上一首按钮事件
        Intent prevIntent = new Intent(this, NotificationReceiver.class);
        prevIntent.setAction(NotificationReceiver.ACTION_PREV);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(
                this,
                1,
                prevIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.btn_prev, prevPendingIntent);

        // 设置播放/暂停按钮事件
        Intent playPauseIntent = new Intent(this, NotificationReceiver.class);
        playPauseIntent.setAction(NotificationReceiver.ACTION_PLAY_PAUSE);
        PendingIntent playPausePendingIntent = PendingIntent.getBroadcast(
                this,
                2,
                playPauseIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.btn_play_pause, playPausePendingIntent);

        // 设置下一首按钮事件
        Intent nextIntent = new Intent(this, NotificationReceiver.class);
        nextIntent.setAction(NotificationReceiver.ACTION_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(
                this,
                3,
                nextIntent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );
        remoteViews.setOnClickPendingIntent(R.id.btn_next, nextPendingIntent);
    }

    // 构建通知
    private Notification buildNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);

        // 设置通知的基本属性
        builder.setSmallIcon(R.mipmap.music)
                .setCustomContentView(remoteViews)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setOngoing(true) // 通知常驻，用户不能手动滑动删除
                .setOnlyAlertOnce(true); // 只在第一次显示时提醒

        return builder.build();
    }

    // 更新通知显示内容
    private void updateNotification() {
        // 更新歌曲信息
        remoteViews.setTextViewText(R.id.tv_title, "第 " + name + " 首");
        remoteViews.setTextViewText(R.id.tv_artist, duration + " / 10");

        // 更新播放/暂停按钮图标
        if (isPlaying) {
            remoteViews.setImageViewResource(R.id.btn_play_pause, R.mipmap.pause);
        } else {
            remoteViews.setImageViewResource(R.id.btn_play_pause, R.mipmap.play);
        }

        // 刷新通知
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.notify(NOTIFICATION_ID, buildNotification());//需要添加权限
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("asdf", "===========onBind==========");
        return new MainBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("asdf", "===========onUnbind==========");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.d("asdf", "===========onRebind==========");
        super.onRebind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("asdf", "===========onDestroy==========");
        mHandler4.removeMessages(0);
        EventBus.getDefault().unregister(this);
        unregisterReceiver(mReceiver);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommandEvent(CommendEvent event) {
        String command = event.getMessage();
        Log.d("asdf", "===========onCommandEvent==========" + command);
        if (command != null) {
            switch (command) {
                case Constants.COMMAND_PLAY:
                    play();
                    break;
                case Constants.COMMAND_PAUSE:
                    pause();
                    break;
                case Constants.COMMAND_LAST:
                    last();
                    break;
                case Constants.COMMAND_NEXT:
                    next();
                    break;
            }
        }
    }

    public void play() {
        Log.d("asdf", "=======play=======");
        mHandler4.sendEmptyMessage(0);
        isPlaying = true;
        updateNotification();
    }

    public void pause() {
        Log.d("asdf", "=======pause=======");
        mHandler4.removeMessages(0);
        isPlaying = false;
        updateNotification();
    }

    public void last() {
        Log.d("asdf", "=======last=======");
        --name;
        duration = 10;
        updateNotification();
    }

    public void next() {
        Log.d("asdf", "=======next=======");
        ++name;
        duration = 10;
        updateNotification();
    }

    public final class MainBinder extends Binder {
        public MainService getService() {
            return MainService.this;
        }
    }

    //EventBus
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (duration == 0) {
                duration = 10;
                name ++;
            }
            MessageEvent messageEvent = new MessageEvent();
            messageEvent.setName(name + "");
            messageEvent.setDuration(duration-- + "");
            EventBus.getDefault().post(messageEvent);
            mHandler.sendEmptyMessageDelayed(0, 1000);
            return false;
        }
    });

    //Listener
    Handler mHandler2 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (duration == 0) {
                duration = 10;
                name ++;
            }
            MessageEvent messageEvent = new MessageEvent();
            messageEvent.setName(name + "");
            messageEvent.setDuration(duration-- + "");
            if (mListener != null) {
                mListener.onMessageChanged(messageEvent);
            }
            mHandler2.sendEmptyMessageDelayed(0, 1000);
            return false;
        }
    });

    //BroadcastReceiver
    Handler mHandler3 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (duration == 0) {
                duration = 10;
                name ++;
            }
            MessageEvent messageEvent = new MessageEvent();
            messageEvent.setName(name + "");
            messageEvent.setDuration(duration-- + "");
            Intent intent = new Intent(Constants.ACTION_SERVICE_TO_ACTIVITY);
            intent.putExtra("message", messageEvent);
            sendBroadcast(intent);
            mHandler3.sendEmptyMessageDelayed(0, 1000);
            return false;
        }
    });

    //来自Activity的Handler
    Handler mHandler4 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (duration == 0) {
                duration = 10;
                name ++;
            }
            MessageEvent messageEvent = new MessageEvent();
            messageEvent.setName(name + "");
            messageEvent.setDuration(duration-- + "");
            Message message = Message.obtain();
            message.obj = messageEvent;
            if (mActivityHandler != null) {
                mActivityHandler.sendMessage(message);
            }
            updateNotification();
            mHandler4.sendEmptyMessageDelayed(0, 1000);
            return false;
        }
    });
}
